iT邦幫忙

0

React從0開始-Day3 組件component

  • 分享至 

  • xImage
  •  

今天要學習Component組件,組件的功能就像是一個容器,他可以把多個HTML元素裝在一起,也就是說可以把網頁拆成不同部分來寫,React會把這些組件結合在一起,進而形成一個網頁。

一、創建組件

創建組件有兩種方式,第一種是class,第二種是function。class較少人使用了,大部分都使用fuction。

function App() {
  
  return (
   <div>hello world</div> 
  )
}

例如這個function App()就代表一個網頁,這個在JavaScript裡面寫HTML就是JSX,至於瀏覽器能夠讀懂JSX是因為JSX經過Vite裡面的編譯工具,轉換成JavaScript。總結,可以把JSX看成JavaScript,只是JSX可以在裡面寫html

創建一個組件並使用:

//創建一個組件
function MyComponent(){
  return <h1>你好</h1>
} 
 
//使用MyComponent()這個組件  
function App() {
  
  return (
   <div><MyComponent></MyComponent></div> 
  )
}

https://ithelp.ithome.com.tw/upload/images/20251015/20170075unGMRXjrl5.png

二、React與Vite如何運作

至於APP.jsx的export default App是把APP組件導出去,並在main.jsx中的import App from './App.jsx’導入APP組件
https://ithelp.ithome.com.tw/upload/images/20251015/201700750GFxuXrHKV.pnghttps://ithelp.ithome.com.tw/upload/images/20251015/20170075xxS5I6JmLR.png

//React把物件轉換成html的過程

ReactDOM.createRoot(document.getElementById('root')).render(
//document.getElementById('root')>>使用DOM api取得id名稱為root的元素
  <React.StrictMode>
    <App /> //根組件
  </React.StrictMode>,
)

三、組件

  1. 通常會使用Pascal Case(將每一個單詞的開頭寫成大寫),用來區分組件以及HTML元素

  2. 組件又分為parent component父組件以及child component子組件,以下面為例,MyComponent 組件被包在App()裡面,所以是子組件,而App為父組件 (樹狀結構)

    function App() {
    
      return (
       <div><MyComponent /></div> 
      )
    }
    
  3. 組件也可以重複使用
    https://ithelp.ithome.com.tw/upload/images/20251015/20170075lGO1SKjXkH.png

  4. 通常會把每個組件獨立成新檔案
    https://ithelp.ithome.com.tw/upload/images/20251015/20170075g19UEDHQ4q.png
    export default ChildComponent;
    再import到App.jsx

import ChildComponent from "./ChildComponent"

function MyComponent(){
  return <ChildComponent />
} 

https://ithelp.ithome.com.tw/upload/images/20251015/20170075lbt2yR7HiY.png

學習影片出處:https://youtu.be/aBTiZfShe-4?si=Igb2aKz3sefA97A5


圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言